package com.qingge.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingge.springboot.common.Result;
import com.qingge.springboot.entity.*;
import com.qingge.springboot.entity.Class;
import com.qingge.springboot.entity.vo.ClassVo;
import com.qingge.springboot.entity.vo.StudentWorkVo;
import com.qingge.springboot.mapper.StudentWorkMapper;
import com.qingge.springboot.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/work")
public class WorkController {


    @Resource
    private StudentService service;

    @Resource
    private  IWorkService workService;

    @Resource
    private CourseTeacherService courseTeacherService;

    @Resource
    private IClassCourseTeacherService classCourseTeacherService;
    
    @Resource
    private StudentWorkService studentWorkService;

    @Resource
    private StudentWorkMapper studentWorkMapper;


    @Resource
    private ISchoolClassService classService;

    /**
     * 通过课程id和教师id查询 ct_id
     * @param courseId
     * @return
     */
    @GetMapping("/getWork/{courseId}/{teacherId}")
    public Result getWorkByCourseAndTeacher(@PathVariable String courseId, @PathVariable String teacherId){
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getCourseId,courseId).eq(CourseTeacher::getTeacherId,teacherId);
        List<CourseTeacher> courseTeachers = courseTeacherService.getBaseMapper().selectList(queryWrapper);
        Stream<Integer> integerStream = courseTeachers.stream().map(CourseTeacher::getId);
        LambdaQueryWrapper<work> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(work::getCtId,integerStream.collect(Collectors.toList()));
        List<work> works = workService.getBaseMapper().selectList(queryWrapper1);
        return Result.success(works);
    }

    /**
     * 保存作业信息
     */
    @PostMapping("/save/")
    public Result saveWork(@RequestBody work work){
        try {
            work.setCreateTime(LocalDateTime.now());
            workService.save(work);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
    }

    @PostMapping
    public Result saveWork(@RequestParam("file") MultipartFile multipartFile,@RequestParam("title")String title,@RequestParam("courseId")Integer courseId,@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @RequestParam(name = "endTime")LocalDateTime endTime,@RequestParam("teacherId")Integer teacherId){
        //根据课程和教师id 查询 ct_id
        LambdaQueryWrapper<CourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseTeacher::getTeacherId, teacherId).eq(CourseTeacher::getCourseId, courseId);
        CourseTeacher courseTeachers = courseTeacherService.getBaseMapper().selectOne(queryWrapper);
        Integer ctId = courseTeachers.getId();

        //保存属于该课程教师下的 班级的所有学生作业信息
        LambdaQueryWrapper<ClassCourseTeacher> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ClassCourseTeacher::getTeacherId,teacherId).eq(ClassCourseTeacher::getCourse,courseId);
        List<ClassCourseTeacher> classCourseTeachers = classCourseTeacherService.getBaseMapper().selectList(queryWrapper1);
        List<Integer> collect = classCourseTeachers.stream().map(ClassCourseTeacher::getClassId).collect(Collectors.toList());

        //查询出学生信息
        LambdaQueryWrapper<Student> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(Student::getClassId,collect);
        List<Student> students = service.getBaseMapper().selectList(queryWrapper2);
        //保存作业
        //查看是否存在该目录
        File file1 = new File("d:/work/"+multipartFile.getOriginalFilename());
        if(!file1.exists()) {
            file1.mkdirs();
        }
        try {
            multipartFile.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //保存作业信息
        work work = new work(null, title, courseId, LocalDateTime.now(), endTime, "", teacherId, ctId, "d:/work/" + multipartFile.getOriginalFilename());
        workService.save(work);
        List<StudentWork> list = new ArrayList<>();
        //循环添加
        students.stream().forEach(item->{
            list.add(new StudentWork(null,ctId,item.getId(),0,"",work.getId()));
        });
        //添加
        studentWorkService.saveBatch(list);
        return Result.success();
    }


    @GetMapping("/getClass/{workId}")
    public Result getCourseClass(@PathVariable Integer workId){
            //根据作业id查询班级
            //1.先查询出作业的 课程id 和 老师id
                work work = workService.getBaseMapper().selectById(workId);
            //2.根据 课程id 和 老师id 查询出班级列表
            LambdaQueryWrapper<ClassCourseTeacher> queryWrapper = new LambdaQueryWrapper<>();
            List<ClassCourseTeacher> classCourseTeachers = classCourseTeacherService.getBaseMapper().selectList(queryWrapper);
            List<Integer> classIds = classCourseTeachers.stream().map(ClassCourseTeacher::getClassId).collect(Collectors.toList());
            List<Class> classList = classService.getBaseMapper().selectBatchIds(classIds);
            //3.封装班级学生该作业的完成比例
            ArrayList<ClassVo> classVos = new ArrayList<>();
            for (Class aClass : classList) {
                ClassVo classVo = new ClassVo();
                BeanUtils.copyProperties(aClass,classVo);
                //查询作业完成比例
                String bili = studentWorkMapper.getBili(aClass.getId(), workId);
                classVo.setBl(bili);
                classVos.add(classVo);
            }
            return Result.success(classVos);
    }

    @GetMapping("/getStudentWork/{ctId}/{stuId}")
    public Result getStudentWork(@PathVariable String ctId, @PathVariable String stuId){
        //1.ctid获取试卷
        LambdaQueryWrapper<StudentWork> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StudentWork::getCtId,ctId).eq(StudentWork::getStuNo,stuId);
        List<StudentWork> list = studentWorkService.getBaseMapper().selectList(queryWrapper);
        //封装 List
        List<StudentWorkVo> studentWorkVos = new ArrayList<>();
        for (StudentWork studentWork : list) {
            Integer workId = studentWork.getWorkId();
            //查询作业信息
            work byId = workService.getById(workId);
            StudentWorkVo studentWorkVo = new StudentWorkVo();
            BeanUtils.copyProperties(studentWork,studentWorkVo);
            studentWorkVo.setWorkTitle(byId.getWorkTitle());
            studentWorkVo.setEndTime(byId.getEndTime());
            studentWorkVo.setWorkFile(byId.getFileUrl());
            studentWorkVos.add(studentWorkVo);
        }
        return Result.success(studentWorkVos);
    }

    @PostMapping("/uploadStudentFile/{stuId}/{workId}")
    public Result studentSubmitWork(@RequestParam("file") MultipartFile file, @PathVariable String stuId, @PathVariable String workId){
       try {
           File file1 = new File("d:/student/" + file.getOriginalFilename());
           if(!file1.exists()){
               file1.mkdirs();
           }
           try {
               file.transferTo(file1);
           } catch (IOException e) {
               e.printStackTrace();
           }
           //修改作业状态
           LambdaQueryWrapper<StudentWork> queryWrapper = new LambdaQueryWrapper<>();
           queryWrapper.eq(StudentWork::getStuNo,stuId).eq(StudentWork::getWorkId,workId);
           StudentWork studentWork1 = studentWorkService.getBaseMapper().selectOne(queryWrapper);
           studentWork1.setIsFinish(1);
           studentWork1.setFileUrl(file1.getPath());
           boolean b = studentWorkService.updateById(studentWork1);
           return Result.success();
       }catch (Exception e){
           return Result.error();
       }

    }
}
